<template>
  <el-card shadow="hover">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">{{ title }}</span>
        <div>
          <el-check-tag v-for="(item, index) in options" :key="index" :checked="current === item.value" 
                        style="margin-right: 8px" @click="handleChoose(item.value)">{{ item.text }}</el-check-tag>
        </div>
      </div>
    </template>
    <div ref="el" id="chart" style="width: 100%;height: 300px;"></div>
  </el-card>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { useResizeObserver } from '@vueuse/core'
// import { getWeekData, getMonthData,getHourData } from '~/api/test.js'
import { getWeekData, getMonthData,getHourData } from '~/api/base.js'

defineProps({
  title: String,
  tip: String,
})

const current = ref('month')
const options = [
  {
    text: '近1个月',
    value: 'month'
  },
  {
    text: '近1周',
    value: 'week'
  },
  {
    text: '近24小时',
    value: 'hour'
  }
]

const handleChoose = type => {
  current.value = type
  // getWData()
  if (current.value === 'week') {
    getWData()
  } else if (current.value === 'month') {
    getMData()
  }
  else if(current.value === 'hour'){
    getHData()
  }
}

let myChart = null;
onMounted(() => {
  const chartDom = document.getElementById('chart');
  if (chartDom) {
    myChart = echarts.init(chartDom)
    getWData()
    getMData()
    getHData()
  }
})

onBeforeUnmount(() => {
  if (myChart) echarts.dispose(myChart)
})

let option = {
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [],
      type: 'line',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }
  ]
}

function getMData() {
  myChart.showLoading()
  getMonthData()
    .then(res => {
      // console.log('getmdata',res)
      let data = res.data
      
      option.xAxis.data = data.x
      option.series[0].data = data.y
      myChart.setOption(option)
    })
    .finally(() => {
      myChart.hideLoading()
    })
}
function getWData() {
  myChart.showLoading()
  getWeekData()
    .then(res => {
      console.log('getWeek',res)
      let data = res.data
      
      option.xAxis.data = data.x
      option.series[0].data = data.y
      myChart.setOption(option)
    })
    .finally(() => {
      myChart.hideLoading()
    })
}
function getHData(){
  myChart.showLoading()
  getHourData()
    .then(res => {
      // console.log('getHour',res)
      let data = res.data
      
      option.xAxis.data = data.x
      option.series[0].data = data.y
      myChart.setOption(option)
    })
    .finally(() => {
      myChart.hideLoading()
    })
}
// vueuse 里面的 useResizeObserve   在使用myChart.resize() 重新自己设定大小
const el = ref(null)
useResizeObserver(el, entries => myChart.resize())
</script>
  